package com.iotteam.androidbase.commen.network.onhttp;

import com.google.gson.Gson;
import com.iotteam.androidbase.R;
import com.iotteam.androidbase.commen.utils.PLog;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.RestRequest;
import com.yanzhenjie.nohttp.rest.StringRequest;

/**
 * Created by lidechen on 5/3/17.
 */

public class JavaBeanRequest<T> extends RestRequest<T> {
    private Class<T> clazz;

    public JavaBeanRequest(String url, Class<T> clazz) {
        this(url, RequestMethod.POST, clazz);
        this.clazz = clazz;
    }

    public JavaBeanRequest(String url, RequestMethod requestMethod, Class<T> clazz) {
        super(url, requestMethod);
        this.clazz = clazz;
    }

    @Override
    public T parseResponse(Headers header, byte[] body) {
        String response = StringRequest.parseResponseString(header, body);

        PLog.i("JavaBeanRequest", response);

        Gson gson = new Gson();
        T b = gson.fromJson(response, clazz);

        // 这里如果数据格式错误，或者解析失败，会在失败的回调方法中返回 ParseError 异常。
        return b;
    }
}
